#coding:utf-8
'''
Created on 2016-5-17

@author: root
'''
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import hashlib
import datetime
import re
import math

from flask import request, redirect

from app.utils.config import SECRET_KEY


def encrypt(props):
    """生成加密码
    """
    parm_items = sorted(props.items(), key=lambda d: d[0])
    parmlist = ["%s=%s"%item for item in parm_items]
    source_str = "&".join(parmlist)+ SECRET_KEY
    sha = hashlib.sha1(source_str)
    return sha.hexdigest().lower()

def check_crypt(props,verification):
    """验证加密码
    """
    return encrypt(props)==verification

def setSecretCookie(response,key,value):
    """设置安全加密cookie
    """
    response.set_cookie(key, value)
    response.set_cookie("%s_sign"%key, encrypt({key:value}))
    
def setMobileSecretCookie(response,key,value):
    """设置安全加密cookie
    """
    response.set_cookie(key, value)
    response.set_cookie("%s_sign"%key, encrypt({key:value}))

def getSecretCookie(request,key):
    """获取安全cookie信息
    """
    cookie = request.cookies
    key_value = cookie.get(key)
    sign_key = "%s_sign"%key
    signature = cookie.get(sign_key)
    if check_crypt({key:key_value}, signature):
        return key_value
    return None

def refresh_cookie(response):
    user_email_id = getSecretCookie(request, "user_email_id")
    if user_email_id:
#         delSecretCookie(response,"user_email_id")
        setSecretCookie(response, "user_email_id", user_email_id)

def delSecretCookie(response,key):
    """清理cookie
    """
    response.delete_cookie(key)
    response.delete_cookie("%s_sign"%key)



def encrypt_json_token(props,expires_in=7200):
    """创建TimedJSONWebSignatureSerializer token
    """
    s = Serializer(SECRET_KEY,expires_in=expires_in)
    return s.dumps(props)
    
def decrypt_json_token(token,expires_in=7200):
    """解析TimedJSONWebSignatureSerializer token的值
    """
    try:
        s = Serializer(SECRET_KEY,expires_in=expires_in)
        token = s.loads(token)
    except:
        token = None
    return token                    

def verify_cookie(func):
    """验证cookie
    """
    def f(*args,**kwargs):
        user_email_id = getSecretCookie(request, "user_info_id")
        if not user_email_id:
            response = redirect('/')
            return response
        return func(*args,**kwargs)
    f.__name__=func.__name__
    return f

def mobile_verify_cookie(func):
    """验证cookie
    """
    def f(*args,**kwargs):
        user_email_id = getSecretCookie(request, "user_email_id")
        if not user_email_id:
            lang = request.args.get('lang')
            response = redirect('/mobile/account/login?lang='+lang)
            return response
        return func(*args,**kwargs)
    f.__name__=func.__name__
    return f

def check_email(email):
    is_right = False
    if re.match(r'^[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+$',email):  
        is_right = True
    return is_right

def get_pic_md5(fileobj):
    fileobj.save('0.jpg')
    filedata = open('0.jpg').read()
    md5_str = hashlib.md5(filedata).hexdigest()
    return md5_str

if __name__ == '__main__':
    print encrypt({"password":'henkuai.com'})